$().ready(function() {
	$('.question').livequery(function() {
		$(function(){
			$('.mandatory').hideErrors();
		});
		$(".comment-link").click(function(event) {
			closeCommentBlock();
			$(this.parentNode).hide();
			id = '#comment-text_' + ($(this).attr('id'));
			$(id).show("slide");
			event.stopPropagation();
		});
		$(".edit-link").click(function(event) {
			closeCommentBlock();
			$(this.parentNode).hide();
			id = '#answer-edit-text_' + ($(this).attr('id'));
			$(id).show("slide");
			$('#Answer_text',id).val($(this).closest('.actions-block').prev().text());
			event.stopPropagation();
		});
		function closeCommentBlock() {
			$('.to-edit').hide('slide');
			$('.to-comment').hide('slide');
			$('.userError').remove();
			$(".phantom-block").show();
		}
		$('body').click(function(event){
			var block = $(event.target).closest('.to-edit,.to-comment');
			var ignoredBlock = $('.userError','#answer-form');
			if(!block.length && !ignoredBlock.length){
				closeCommentBlock();
			}
		});
		$('.answer').submit(function() {
			if (!$(this).fullValidate()) return false;
		});
	
		// Отметка лучшего вопроса
		$(".make-best").live("click",function(event) {
			thisDiv = $(this);
			$.ajax({
				dataType: 'json',
				url: W_AJAX + 'question/best-answer',
				type: 'POST',
				data: {
						ID_answer: $(this).attr('id')
					},
				success: function(data) {
					if(data.result == 'OK') {
						idBestOld = $('.is-the-best').attr('id');
						$('.is-the-best').replaceWith('<div title="Лучший ответ" id="' + idBestOld + '" class="make-best"></div>');
						thisDiv.replaceWith('<div id="' + thisDiv.attr('id') + '" class="is-the-best">ЛУЧШИЙ ОТВЕТ</div>');
					}
				}	
			});
		});
	
		// Коммент к вопросу
		$('.comment-form').submit(function() {
			$objForm = $(this);
			if($objForm.fullValidate()) {
				$.ajax({
					dataType: 'json',
					url: W_AJAX + 'question/comment',
					type: 'POST',
					data: {
						text: $('#QuestionComment_text',$objForm).val(),
						ID_user: $('#QuestionComment_ID_user',$objForm).val(),
						ID_answer: $('#QuestionComment_ID_answer',$objForm).val()
					},
					success: function(data) {
						if(data.result == 'OK') {
							closeCommentBlock();
							$objForm.find('textarea').val('');
							$objForm.parent().next().append(data.data.commentBlockText);
						}
					}	
				});
				$('.userError').remove();
			}
			return false;
		});
	});
});